const db = require('../db/index')
const _ = require('lodash')

function reqOne(params) {
    var sql = "select * from sp_report_1"
    db.query(sql, (err, result) => {
        if (err) return params(err)
            // console.log(result);
            // res.ResData(result)
        var areakeyResult = {}
        var areakeys = _.union(_.map(result, "rp1_area"))
        var dateKeys = _.union(_.map(result, function(record) {
            str = record.rp1_date.getFullYear() + "-" + (record.rp1_date.getMonth() + 1) + "-" + record.rp1_date.getDate()
            return str
        }))
        console.log(dateKeys);
        for (idx in result) {
            var record = result[idx]
            var datekey = record.rp1_date.getFullYear() + "-" + (record.rp1_date.getMonth() + 1) + "-" + record.rp1_date.getDate()
            console.log(record['rp1_area']);
            if (!areakeyResult[record['rp1_area']]) {
                areakeyResult[record['rp1_area']] = {}
            }
            areakeyResult[record['rp1_area'][datekey]] = record
        }
        // console.log(areakeyResult);
        var series = []
        _(areakeys).forEach(function(areakey) {
            var data = [];
            _(dateKeys).forEach(function(datekey) {
                if (areakeyResult[areakey][datekey]) {
                    data.push(areakeyResult[areakey][datekey]["rp1_user_count"])
                } else {
                    data.push(0)
                }
            })
            console.log(data);
            series.push({
                name: areakey,
                type: 'line',
                areaStyle: {},
                stack: '总量',
                data: data
            })
        })
        var data = {
            title: {
                text: '用户来源'
            },
            legend: {
                data: areakeys
            },
            xAxis: [{
                data: dateKeys
            }],
            yAxis: [
                { type: 'value' }
            ],
            series: series
        }
        params(null, data)
    })

}
exports.getRep = (req, res) => {
    // console.log(1);
    var typeId = req.params.typeId
        // 参数验证
        // if(!typeId) return res.ResData('不能为空')
        // 参数必须为数字
    reqOne((err, data) => {
        if (err) res.ResData(err)
        res.ResData('获取报表数据成功！', 200, data)
    })
}